// 维修上报页面逻辑
import http from '../../../utils/https'

Page({
  data: {
    houses: [], // 房屋列表（从接口获取）
    houseIds: [], // 房屋ID列表（与房屋名称对应）
    houseIndex: 0,
    selectedItem: '',
    title: '',
    description: '',
    phone: '',
    date: '',
    images: [],
    residentId: null // 住户ID
  },

  onLoad: function (options) {
    if (options.itemName) {
      this.setData({
        selectedItem: decodeURIComponent(options.itemName)
      });
    }
    // 加载住户ID并获取房屋列表
    this.loadResidentId();
  },

  // 获取本地存储的住户ID
  loadResidentId() {
    try {
      // 从独立存储的residentId键获取，而不是userInfo对象内
      const residentId = wx.getStorageSync('residentId');
      if (residentId && !isNaN(Number(residentId))) {
        this.setData({ residentId: Number(residentId) }, () => {
          this.loadHouseList(); // 获取房屋列表
        });
      } else {
        this.handleError('未获取到有效住户信息');
        setTimeout(() => wx.navigateTo({ url: '/pages/complete/complete' }), 1500);
      }
    } catch (err) {
      console.error('获取本地存储失败:', err);
      this.handleError('数据读取失败，请重试');
    }
  },

  // 从接口获取房屋列表
  loadHouseList() {
    const { residentId } = this.data;
    
    // 使用新接口地址
    http.get(`house/house/housesByResident/${residentId}`)
      .then(res => {
        if (res.code === 200) {
          const houseList = res.data || [];
          
          // 提取房屋名称和ID
          const houses = houseList.map(item => item.houseNumber);
          const houseIds = houseList.map(item => item.houseId);
          
          this.setData({
            houses,
            houseIds,
            houseIndex: houseList.length > 0 ? 0 : -1
          });
        } else {
          throw new Error(res.msg || '获取房屋列表失败');
        }
      })
      .catch(err => {
        console.error('获取房屋列表失败:', err);
        this.handleError(err.message || '获取房屋信息失败，请稍后重试');
      });
  },

  bindHouseChange: function(e) {
    this.setData({
      houseIndex: e.detail.value
    });
  },

  bindDateChange: function(e) {
    this.setData({
      date: e.detail.value
    });
  },

  // 新增：处理标题输入
  onTitleInput: function(e) {
    this.setData({
      title: e.detail.value
    });
  },

  // 新增：处理问题描述输入
  onDescriptionInput: function(e) {
    this.setData({
      description: e.detail.value
    });
  },

  // 新增：处理电话输入
  onPhoneInput: function(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  goToMaintenanceItem: function() {
    wx.navigateTo({
      url: '/service/pages/maintenanceItem/maintenanceItem'
    });
  },

  chooseImage: function() {
    const that = this;
    wx.chooseImage({
      count: 3,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        that.setData({
          images: that.data.images.concat(res.tempFilePaths)
        });
      }
    });
  },

  previewImage: function(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: this.data.images
    });
  },

  submitRepair: function() {
    // 获取当前选中的房屋ID
    const currentHouseId = this.data.houseIds[this.data.houseIndex];
    
    // 表单验证
    if (this.data.houseIndex === -1) {
        wx.showToast({
            title: '请选择房屋',
            icon: 'none'
        });
        return;
    }
    
    if (!this.data.selectedItem) {
        wx.showToast({
            title: '请选择维修项目',
            icon: 'none'
        });
        return;
    }
    
    if (!this.data.description) {
        wx.showToast({
            title: '请填写问题描述',
            icon: 'none'
        });
        return;
    }
    
    // 提交数据（包含houseId）
    const submitData = {
        houseId: currentHouseId,
        repairItem: this.data.selectedItem,
        repairTitle: this.data.title,
        problem: this.data.description,
        appointmentDate: this.data.date,
        residentId: this.data.residentId
    };
    
    wx.showLoading({
        title: '提交中...',
        mask: true
    });
    
    // 提交维修数据
    http.post('property/repair', submitData)
        .then(res => {
            wx.hideLoading();
            if (res.code === 200) {
                wx.showToast({
                    title: '提交成功',
                    icon: 'success',
                    duration: 2000
                });
                setTimeout(() => {
                    wx.navigateBack();
                }, 2000);
            } else {
                throw new Error(res.msg || '提交失败');
            }
        })
        .catch(err => {
            wx.hideLoading();
            console.error('提交失败:', err);
            wx.showToast({
                title: err.message || '提交失败，请重试',
                icon: 'none',
                duration: 3000
            });
        });
},

  // 错误提示处理
  handleError(message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 3000
    });
  }
});